package com.ztsoft.user.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChargeCalculateUtils {
    private ChargeCalculateUtils() {}

    private static class Level {
        private Double more;
        private Double less;
        private Double rate;

        public Level(Double more, Double less, Double rate) {
            this.more = more;
            this.less = less;
            this.rate = rate;
        }

        public Double getMore() {
            return more;
        }
        public Double getLess() {
            return less;
        }
        public Double getRate() {
            return rate;
        }
    }

    private static final Map<String, List<Level>> LEVEL_MAP = new HashMap<>();

    static {
        List<Level> product = new ArrayList<>();
        product.add(new Level(100.00, 0.00, 0.015));
        product.add(new Level(500.00, 100.00, 0.011));
        product.add(new Level(1000.00, 500.00, 0.008));
        product.add(new Level(5000.00, 1000.00, 0.005));
        product.add(new Level(10000.00, 5000.00, 0.0025));
        product.add(new Level(100000.00, 10000.00, 0.0005));
        product.add(new Level(99999999999999.99, 100000.00, 0.0001));

        List<Level> service = new ArrayList<>();
        service.add(new Level(100.00, 0.00, 0.015));
        service.add(new Level(500.00, 100.00, 0.008));
        service.add(new Level(1000.00, 500.00, 0.0045));
        service.add(new Level(5000.00, 1000.00, 0.0025));
        service.add(new Level(10000.00, 5000.00, 0.001));
        service.add(new Level(100000.00, 10000.00, 0.0005));
        service.add(new Level(99999999999999.99, 100000.00, 0.0001));

        List<Level> project = new ArrayList<>();
        project.add(new Level(100.00, 0.00, 0.01));
        project.add(new Level(500.00, 100.00, 0.007));
        project.add(new Level(1000.00, 500.00, 0.0055));
        project.add(new Level(5000.00, 1000.00, 0.0035));
        project.add(new Level(10000.00, 5000.00, 0.002));
        project.add(new Level(100000.00, 10000.00, 0.0005));
        project.add(new Level(99999999999999.99, 100000.00, 0.0001));

        LEVEL_MAP.put("product", product);
        LEVEL_MAP.put("service", service);
        LEVEL_MAP.put("project", project);
    }

    public static String calculate(String type, String amount) {
        double a = calculate(type, Double.parseDouble(amount), 0) * 1000000; //原单位万元，现改为元，再保留2位小数
        return String.valueOf(Math.round(a)/100.00);
    }

    private static Double calculate(String type, Double num, int index) {
        Level level = LEVEL_MAP.get(type).get(index);
        return num <= level.getMore() ? (num - level.getLess()) * level.getRate() : (level.getMore() - level.getLess()) * level.getRate() + calculate(type, num, index+1);
    }

}
